﻿#include<iostream>
#include"dllmain.h"

unsigned char* runCV2(int& width, int& height, int& channels,const char* path)
{
	//const char* path = "Setting\\template.jpg";
	Mat img = runAlgorithm(path);
	//Mat img = runAlgorithm();
	if (img.data == NULL)
	{
		throw "img is NULL!";
	}
	return trans(width, height, channels, img);
}

void releasRoom()
{
	if (imgBuffer==NULL)
	{
		return;
	}
	free(imgBuffer);
	imgBuffer = NULL;
}

unsigned char* trans(int& width,int& height,int& channels,Mat img)
{
	if (img.channels() == 1)
	{
		cvtColor(img, img, COLOR_GRAY2BGR);
	}

	width = img.cols;
	height = img.rows;
	channels = img.channels();
	int strid = (img.cols * channels + 3) / 4 * 4;

	imgBuffer = static_cast<unsigned char*>(malloc(strid * height * sizeof(unsigned char)));
	if (imgBuffer != NULL)
	{
		int totalPixel = width * height * channels;
		for (int i = 0;i < height;i++)
		{
			int rowUpPixel = i * strid;//已经复制的像素行,i:行数,strid:每一行实际占用的内存大小，bitmap内存对齐，strid必须是4的倍数
			for (int j = 0;j < width * channels;j++)
			{
				imgBuffer[rowUpPixel + j] = img.data[i * width * channels + j];//i:行数;j:列，width:mat对象中没有bitmap内存对齐机制，所以width就是图片宽度×通道数
			}
		}
	}
	return imgBuffer;
}

Mat runAlgorithm(const char* path)
{
	/*Mat imgSrc = imread("C:\\Users\\uwuxj499\\Pictures\\data\\1.bmp", IMREAD_GRAYSCALE);
	Mat tmplt1 = imread("C:\\Users\\uwuxj499\\Pictures\\data\\template.bmp", IMREAD_GRAYSCALE);
	Mat tmplt2 = imread("C:\\Users\\uwuxj499\\Pictures\\data\\template2.bmp", IMREAD_GRAYSCALE);*/

	//Mat imgSrc = imread("Setting\\template.jpg", IMREAD_GRAYSCALE);
	Mat imgSrc = imread(path, IMREAD_GRAYSCALE);
	Mat tmplt1 = imread("Setting\\target1.jpg", IMREAD_GRAYSCALE);
	Mat tmplt2 = imread("Setting\\target2.jpg", IMREAD_GRAYSCALE);

	Mat result;
	double minVal, maxVal;
	cv::Point minLoc, maxLoc;

	matchTemplate(imgSrc, tmplt1, result, TM_CCOEFF_NORMED);
	cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);
	Rect r1 = Rect(maxLoc.x,maxLoc.y,tmplt1.cols,tmplt1.rows);

	matchTemplate(imgSrc,tmplt2,result,TM_CCOEFF_NORMED);
	cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);
	Rect r2 = Rect(maxLoc.x, maxLoc.y, tmplt2.cols, tmplt2.rows);

	/*Mat tmplt = imread("C:\\Users\\uwuxj499\\Pictures\\data\\template.bmp", IMREAD_GRAYSCALE);
	Mat tmpltTrans;
	for (int angl=0;angl<360;angl+=2)
	{
		tmpltTrans = rotate();
		matchTemplate(imgSrc, tmplt2, result, TM_CCOEFF_NORMED);
		cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);
		Rect r2 = Rect(maxLoc.x, maxLoc.y, tmplt2.cols, tmplt2.rows);
	}*/

	cvtColor(imgSrc,imgSrc,COLOR_GRAY2BGR);
	cv::rectangle(imgSrc, r1, Scalar(0, 255, 0), 9);
	cv::rectangle(imgSrc, r2, Scalar(0, 0, 255), 9);

	return imgSrc;
}